package org.crazyit.activiti_d3._2_UserGroupCandidate;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;

import java.util.UUID;

public class UserGroupCandidate {

    public static void main(String[] args) {

        //1. 创建流程引擎
        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();

        //2. 得到流程存储服务实例
        RepositoryService repositoryService = engine.getRepositoryService();

        //3. 得到身份服务组件
        IdentityService identityService = engine.getIdentityService();

        //4. 部署流程描述文件
        Deployment dep = repositoryService.createDeployment().addClasspathResource("candidateUser.bpmn").deploy();

        //5. 查询流程定义实体
        ProcessDefinition def = repositoryService.createProcessDefinitionQuery().deploymentId(dep.getId()).singleResult();

        //5. 写入用户数据
        String id1 = UUID.randomUUID().toString();
        String id2 = UUID.randomUUID().toString();
        createUserGroup(identityService, id1,"group1","用户组1");
        createUserGroup(identityService, id2,"group2","用户组2");

        //6. 设置用户与流程定义的关系 (设置权限)
        repositoryService.addCandidateStarterGroup(def.getId(), id1);
        repositoryService.addCandidateStarterGroup(def.getId(), id2);

    }

    /**
     * 创建用户
     * @param identityService   身份服务组件
     * @param id                用户组ID
     * @param name              用户组名
     * @param type              用户组类型
     */
    public static void createUserGroup(IdentityService identityService, String id, String name, String type) {

        //1. 调用newGroup() 方法创建Group 实例
        Group group = identityService.newGroup(id);
        group.setName(name);
        group.setType(type);

        //2. 保存到数据库
        identityService.saveGroup(group);

    }

}
